<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    @register="registerModal"
    @ok="handleSubmit"
    width="600px"
    title="配置权限"
  >
    <div class="permission-config">
      <div class="role-info mb-4">
        <span class="font-bold">角色名称：</span>
        <span>{{ roleName }}</span>
      </div>
      <a-spin :spinning="loading">
        <a-tree
          v-model:checkedKeys="checkedKeys"
          checkable
          :tree-data="treeData as any"
          :field-names="{ title: 'zhName', key: 'name', children: 'children' }"
          :default-expand-all="true"
        />
      </a-spin>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup name="ViewsTbRolePermissionConfig">
  import { ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Tree as ATree, Spin as ASpin } from 'ant-design-vue';
  import { getMenuTree, saveRole } from '/@/api/tb/role';
  import type { MenuTreeNode, Role } from '/@/api/tb/role';

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const roleData = ref<Role | null>(null);
  const roleName = ref<string>('');
  const loading = ref(false);
  const treeData = ref<MenuTreeNode[]>([]);
  const checkedKeys = ref<string[]>([]);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    loading.value = true;

    // 重置状态
    roleData.value = null;
    roleName.value = '';
    checkedKeys.value = [];
    treeData.value = [];

    try {
      // 保存角色完整数据
      roleData.value = data;
      roleName.value = data.name || '';

      // 从角色数据中获取当前权限
      checkedKeys.value = data.menus || [];

      // 获取菜单树
      const menuTreeResult = await getMenuTree();
      treeData.value = menuTreeResult || [];
    } catch (error: any) {
      console.error('加载权限配置失败:', error);
      showMessage('加载权限配置失败', 'error');
    } finally {
      loading.value = false;
      setModalProps({ loading: false });
    }
  });

  async function handleSubmit() {
    try {
      if (!roleData.value) {
        showMessage('缺少角色数据', 'error');
        return;
      }

      setModalProps({ confirmLoading: true });

      // 构建更新请求，包含 roleId 和更新后的 menus
      const updateData: Role = {
        roleId: roleData.value.roleId || roleData.value.id,
        name: roleData.value.name,
        menus: checkedKeys.value,
      };

      await saveRole(updateData);

      showMessage('权限配置保存成功！');
      setTimeout(closeModal);
      emit('success');
    } catch (error: any) {
      const errorMessage = error?.message || error?.data?.message || '未知错误';
      showMessage(`保存权限配置失败: ${errorMessage}`, 'error');
      console.error('保存权限配置失败:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .permission-config {
    padding: 10px 0;

    .role-info {
      padding: 12px;
      background-color: #f5f5f5;
      border-radius: 4px;
    }
  }
</style>
